package org.xilin

class TheClass {
    Course course
    Student student
    boolean bookIncluded = false

    static TheClass link(Course course, Student student) {
	def c = TheClass.findByCourseAndStudent(course, student)
	if (!c) {
            c = new TheClass()
            if(course.book) {
                c.bookIncluded = true
            }
            student?.addToClasses(c)
            course?.addToClasses(c)
            c.save(flush: true).refresh()
            student.save(flush:true).refresh()
            course.save(flush:true).refresh()
        }
        return c
    }

    static void unlink(Course course, Student student) {
        def c = TheClass.findByCourseAndStudent(course, student)

        if (c) {
            if(c.bookIncluded) {
                course.book.reserve--
                course.book.save(flush:true)
            }
            student?.removeFromClasses(c)
            course?.removeFromClasses(c)
            c.delete(flush:true)
        }
    }

    static void unlink(Student student) {
        def classList = TheClass.findAllByStudent(student)

        classList.each {
            unlink(it.course, student)
        }
    }
}
